﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Srs.Sample.UI.CustomerService;

namespace Srs.Sample.UI.WebParts
{
    public class SrsSimpleWebPart : WebPart
    {
        Label lblHello;
        Label lblCsName;
        TextBox txtCstId;
        Label errMsg;

        //TODO: Exception handling
        //TODO: Globalization
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            string userName = this.Context.User.Identity.Name;
            string tagName = SPContext.Current.Web.Url;

            lblHello = new Label();
            //lblHello.Text = String.Format(RESOURCES.srsSampleUI.strHelloSimple, userName);
            lblHello.Text = "Hello there " + userName + " welcome to " + tagName;
            Controls.Add(lblHello);

            this.AddLineBreak();
            //WebPartUtilities.LineBreak(this);


            txtCstId = new TextBox();
            Controls.Add(txtCstId);

            Button btnSubmit = new Button();
            btnSubmit.Text = "Get customer name";
            btnSubmit.Click += new EventHandler(btnSubmit_Click);
            Controls.Add(btnSubmit);

            this.AddLineBreak();


            lblCsName = new Label();
            Controls.Add(lblCsName);

            this.AddLineBreak();


            errMsg = new Label();
            errMsg.EnableViewState = false;
            Controls.Add(errMsg);

        }

        void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                int cltId;
                if (int.TryParse(txtCstId.Text, out cltId))
                {
                    lblCsName.Text = GetClientData(cltId);
                }
                errMsg.Text = String.Empty;
            }
            catch (Exception ex)
            {
                errMsg.Text = ex.Message;
            }
        }


        string GetClientData(int custId)
        {
            using (CustomerServiceClient svc = new CustomerServiceClient())
            {
                Customer cst = svc.GetCustomer(custId);
                return cst.Name;
            }
        }
    }
}
